<?php
class Auth extends ClassBase{

	public function logout(){
		$_SESSION = array();
		F::get()->Tpl()->addMessage('Auth','Logged off');
		F::get()->Tpl()->redirect('home');
	}
	
	public function login($username, $password){
		$resp = F::get()->APICaller()->submit('login', array('username'=>$username,'password'=>$password) );
		
		
		if( $resp['userID'] > 0 ){
			$_SESSION['auth']['loggedIn'] 			  = true;
			$_SESSION['auth']['user']['id'] 		 	= $resp['userID'];
			$_SESSION['auth']['user']['username'] = $username;
			F::get()->Tpl()->addMessage('Auth','Login Successful');
		}else{
			F::get()->Tpl()->addMessage('Auth','Login failed for '.$username, 'error');
		}
		F::get()->Tpl()->redirect('home');
	}
	
	public function post($switch){
		switch( $switch ) {
			case 'login':{
				$this->login($_POST['login']['username'], $_POST['login']['password']);
				break;
			}
			case 'logout':{
				$this->logout();
				break;
			}
		}
	}
	public function isLoggedIn(){
		return (bool)$_SESSION['auth']['loggedIn'] ;
	}
	public function getLoggedInUserName(){
		return  $_SESSION['auth']['user']['username'];
	}
	public function isAdmin(){
		return (bool)$_SESSION['auth']['user']['id'] == 1 ;
	}
	
	
	/**
	* Creates a session key for Auth
	* @param $formKey TableBase::getFormKey()
	* @return string Token that is saved to session 
	*/
	public function createSessionToken($formKey){ 
		$token = uniqid(rand(), true);
		$_SESSION['token'][md5($formKey)] = $token;
		return $token;
	}
	public function checkSessionToken($formToken, $tokenToCheck){
		$valid = false;
		if( isset( $_SESSION['token'][md5($formToken)] )  && !empty( $tokenToCheck ) ){
			$valid =  $_SESSION['token'][md5($formToken)] == $tokenToCheck;
		}
		return $valid;
	}
	public function clearTokens(){
		unset($_SESSION['token']);
	}
}
?>
